// SSE连接管理器
class SSEManager {
  constructor() {
    this.connections = new Map() // 存储所有SSE连接
    this.heartbeatInterval = null
    this.heartbeatIntervalMs = 30000 // 30秒心跳
    this.maxConnections = 1000 // 最大连接数
    this.connectionTimeout = 300000 // 5分钟无活动超时
  }

  // 添加连接
  addConnection(connectionId, ctx) {
    if (this.connections.size >= this.maxConnections) {
      console.log('SSE连接数已达上限，拒绝新连接')
      return false
    }

    const connection = {
      id: connectionId,
      ctx: ctx,
      createdAt: Date.now(),
      lastActivity: Date.now(),
      isActive: true
    }

    this.connections.set(connectionId, connection)
    console.log(`SSE连接已添加: ${connectionId}, 当前连接数: ${this.connections.size}`)
    
    // 启动心跳机制
    this.startHeartbeat()
    
    return true
  }

  // 移除连接
  removeConnection(connectionId) {
    const connection = this.connections.get(connectionId)
    if (connection) {
      connection.isActive = false
      this.connections.delete(connectionId)
      console.log(`SSE连接已移除: ${connectionId}, 当前连接数: ${this.connections.size}`)
    }
  }

  // 更新连接活动时间
  updateActivity(connectionId) {
    const connection = this.connections.get(connectionId)
    if (connection) {
      connection.lastActivity = Date.now()
    }
  }

  // 发送消息到指定连接
  sendToConnection(connectionId, message) {
    const connection = this.connections.get(connectionId)
    if (connection && connection.isActive) {
      try {
        const sseMessage = `data: ${JSON.stringify(message)}\n\n`
        connection.ctx.res.write(sseMessage)
        this.updateActivity(connectionId)
        return true
      } catch (error) {
        console.log(`发送消息到连接 ${connectionId} 失败:`, error.message)
        this.removeConnection(connectionId)
        return false
      }
    }
    return false
  }

  // 广播消息到所有连接
  broadcast(message) {
    const activeConnections = []
    for (const [connectionId, connection] of this.connections) {
      if (this.sendToConnection(connectionId, message)) {
        activeConnections.push(connectionId)
      }
    }
    console.log(`广播消息到 ${activeConnections.length} 个连接`)
    return activeConnections.length
  }

  // 发送心跳消息
  sendHeartbeat(connectionId) {
    return this.sendToConnection(connectionId, {
      type: 'heartbeat',
      timestamp: Date.now()
    })
  }

  // 启动心跳机制
  startHeartbeat() {
    if (this.heartbeatInterval) return

    this.heartbeatInterval = setInterval(() => {
      this.cleanupInactiveConnections()
      this.sendHeartbeatToAll()
    }, this.heartbeatIntervalMs)
  }

  // 停止心跳机制
  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
  }

  // 发送心跳到所有连接
  sendHeartbeatToAll() {
    for (const connectionId of this.connections.keys()) {
      this.sendHeartbeat(connectionId)
    }
  }

  // 清理非活跃连接
  cleanupInactiveConnections() {
    const now = Date.now()
    const toRemove = []

    for (const [connectionId, connection] of this.connections) {
      // 检查连接是否超时
      if (now - connection.lastActivity > this.connectionTimeout) {
        toRemove.push(connectionId)
      }
    }

    toRemove.forEach(connectionId => {
      console.log(`清理超时连接: ${connectionId}`)
      this.removeConnection(connectionId)
    })
  }

  // 获取连接统计信息
  getStats() {
    const now = Date.now()
    let activeCount = 0
    let totalAge = 0

    for (const connection of this.connections.values()) {
      if (connection.isActive) {
        activeCount++
        totalAge += now - connection.createdAt
      }
    }

    return {
      totalConnections: this.connections.size,
      activeConnections: activeCount,
      averageAge: activeCount > 0 ? Math.round(totalAge / activeCount / 1000) : 0, // 秒
      maxConnections: this.maxConnections
    }
  }

  // 关闭所有连接
  closeAllConnections() {
    for (const [connectionId, connection] of this.connections) {
      try {
        connection.ctx.res.end()
      } catch (error) {
        console.log(`关闭连接 ${connectionId} 失败:`, error.message)
      }
    }
    this.connections.clear()
    this.stopHeartbeat()
  }
}

// 创建全局实例
const sseManager = new SSEManager()

export default sseManager
